#include "wuStopMotion.h"

wuStopMotion::wuStopMotion()
{
}

wuStopMotion::~wuStopMotion()
{
}


void wuStopMotion::setup(vector <wuSkin> * _skins)
{
   	skins = _skins;

    offset.x=0;
    offset.y=0;
    counter = 0;
    framePtr = 0;
    bisAlive = false;
    bReverse = false;
    bGo = false;
    bStopsAtEnd = false;
    bLoop = false;
}

void wuStopMotion::update()
{
        if(bGo)
            counter++;

        if(counter==2)
        {
            counter=0;
            if(bReverse)
                framePtr--;
            else
                framePtr++;
        }

        if(framePtr == (*skins).size()-1 && !bReverse)
        {
            if(bLoop)
            {
                framePtr = 0;
            }else
            if(bStopsAtEnd)
            {
                bGo = false;
            }else
            {
                framePtr = 0;
                bisAlive = false;
                bGo = false;
            }
        }

        if(framePtr == 0 && bReverse)
        {
            if(bLoop)
            {
                framePtr = (*skins).size()-1;
            }else
            if(bStopsAtEnd)
            {
                bGo = false;
            }else
            {
                bGo = false;
                bisAlive = false;
            }

        }
}

void wuStopMotion::draw(bool bDrawlines, int _offX)
{
	ofSetColor(255, 255, 255);

    // draw Skin at position
    ofPushMatrix();
        ofEnableAlphaBlending();
        (*skins)[framePtr].draw(_offX+offset.x, offset.y);
        ofDisableAlphaBlending();
    ofPopMatrix();

}

void wuStopMotion::clear()
{
    offset.x=0;
    offset.y=0;
    counter = 0;
    framePtr = 0;
    bisAlive = false;
    bGo = false;
}

void wuStopMotion::capture(ofRectangle _rect)
{
    bisAlive = true;
    bGo = true;
    if(bReverse)
    {
        framePtr = (*skins).size()-1;
        offset.x = (_rect.x + (_rect.width)/2) - (*skins)[(*skins).size()-1].posSkin.x;
        offset.y = (_rect.y + (_rect.height)/2) - (*skins)[(*skins).size()-1].posSkin.y;
    }
    else
    {
        framePtr = 0;
        offset.x = (_rect.x + (_rect.width)/2) - (*skins)[0].posSkin.x;
        offset.y = (_rect.y + (_rect.height)/2) - (*skins)[0].posSkin.y;
    }
}

bool wuStopMotion::isAlive()
{
    return bisAlive;
}

void wuStopMotion::reverse(bool _rev)
{
    bReverse = _rev;
}
void wuStopMotion::setFreeze_end(bool _bFreeze)
{
    bStopsAtEnd = _bFreeze;
}
void wuStopMotion::setLoop(bool _bloop)
{
    bLoop = _bloop;
}
